package api

import (
	"context"
	"net/http"

	"github.com/gorilla/mux"

	"github.com/ovh/cds/engine/api/application"
	"github.com/ovh/cds/engine/api/event"
	"github.com/ovh/cds/engine/service"
	"github.com/ovh/cds/sdk"
)

func (api *API) postVulnerabilityHandler() service.Handler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		vars := mux.Vars(r)
		key := vars[permProjectKey]
		appName := vars["applicationName"]

		vulnID, errV := requestVarInt(r, "id")
		if errV != nil {
			return sdk.WrapError(errV, "Unable to read ID")
		}

		var v sdk.Vulnerability
		if err := service.UnmarshalBody(r, &v); err != nil {
			return sdk.WrapError(err, "Unable to read body")
		}

		app, err := application.LoadByName(ctx, api.mustDB(), key, appName)
		if err != nil {
			return sdk.WrapError(err, "unable to load application")
		}

		vulnDB, err := application.LoadVulnerability(api.mustDB(), app.ID, vulnID)
		if err != nil {
			return sdk.WrapError(err, "unable to load vulnerability")
		}

		old := vulnDB

		vulnDB.Ignored = v.Ignored

		if err := application.UpdateVulnerability(api.mustDB(), vulnDB); err != nil {
			return sdk.WrapError(err, "unable to update vulnerability")
		}

		event.PublishApplicationVulnerabilityUpdate(ctx, key, appName, old, vulnDB, getUserConsumer(ctx))
		return service.WriteJSON(w, vulnDB, http.StatusOK)
	}
}
